package com.bridge.utils.rpc;

import com.alibaba.fastjson.JSON;
import com.bridge.domain.ConfigDTO;
import com.bridge.exception.BridgeProcessFailException;
import com.bridge.enums.BridgeErrorEnum;
import com.bridge.utils.rpc.http.HttpClientUtils;
import org.springframework.util.StringUtils;


/**
 * @author Jay
 * @version v1.0
 * @description rpc请求
 * @date 2019-01-03 18:49
 */
public class RpcServiceHandler {


    /**
     * 请求配置项数据
     *
     * @param serverUrl
     * @return
     */
    public static ConfigDTO getConfigList(String serverUrl, String uniqueToken) {
        String apiAddress = serverUrl.concat("/getConfigList?appCode=").concat(uniqueToken);
        return httpPostRequest(apiAddress, ConfigDTO.class);
    }


    /**
     * 获取zk地址
     *
     * @param serverUrl
     * @return
     */
    public static String getZkAddress(String serverUrl) {
        String url = serverUrl.concat("/queryZkAddress");
        RpcResponse<String> rpcResponse = httpPostRequest(url);
        return rpcResponse.getResult();
    }


    /**
     * 只带url的post请求
     *
     * @param url
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T httpPostRequest(String url, Class<T> clazz) {
        RpcResponse response = httpPostRequest(url);
        if (response.getResult() != null) {
            return JSON.parseObject(response.getResult().toString().trim(), clazz);
        }
        return null;
    }

    /**
     * 只带url的post请求
     *
     * @param url
     * @return
     */
    public static RpcResponse httpPostRequest(String url) {
        String result = HttpClientUtils.httpPostRequest(url);
        if (StringUtils.isEmpty(result)) {
            throw new BridgeProcessFailException(BridgeErrorEnum.RPC_ERROE);
        }
        RpcResponse response = JSON.parseObject(result, RpcResponse.class);
        if (response == null || !response.getSuccess()) {
            throw new BridgeProcessFailException(BridgeErrorEnum.RPC_ERROE);
        }
        return response;
    }


}
